﻿using System;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Windows;
using System.Xml.Linq;
using Microsoft.Win32;
using WpfApp1.Enums;
using System.Windows.Controls;
using System.Management;
using System.Text;
using System.Reflection;
using WpfApp1.Entity;
using WpfApp1.Controller;
using System.Text.Json;
using static WpfApp1.Entity.Configurations;
using Newtonsoft.Json.Linq;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        private static Configurations.WebServerInfo _webServerInfo;
        private Service.CertificateService.CertificateService _certificateService = new Service.CertificateService.CertificateService();
        private CertificateItem _certificateItem = null;

        static MainWindow()
        {
            parseSettings();
            FileController.GetFieldFromJsonByName(Directory.GetCurrentDirectory() + "/Config/appsettings.json", "token");
        }

        private static void parseSettings()
        {
            string baseDirectory = Directory.GetCurrentDirectory();
            string filePath = baseDirectory + "/Config/appsettings.json";
            if (File.Exists(filePath))
            {
                try
                {
                    string jsonContent = File.ReadAllText(filePath);

                    // 解析 JSON 文本为 JsonDocument
                    using (JsonDocument doc = JsonDocument.Parse(jsonContent))
                    {
                        // 获取 webServer 元素
                        if (doc.RootElement.TryGetProperty("webServer", out JsonElement webServerElement))
                        {
                            // 将 webServer 元素反序列化为 WebServer 对象
                            _webServerInfo = JsonSerializer.Deserialize<Configurations.WebServerInfo>(webServerElement.GetRawText());

                            string ip = _webServerInfo.ip;
                            int port = _webServerInfo.port;
                            string apiUrl = $"http://{ip}:{port}";
                            FileController.ApiUrl = apiUrl;
                        }
                        else
                        {
                            Console.WriteLine("未找到 webServer 节点。");
                        }
                    }
                }
                catch(Exception ex)
                {
                    Console.WriteLine($"解析 JSON 文件时出现错误: {ex.Message}");
                }
            }
        }

        private void InitGUI()
        {
            // 为doctype combox添加类型选项
            Array enumValues = Enum.GetValues(typeof(CertificateType));

            foreach (var value in enumValues)
            {   
                cmbDocType.Items.Add(value.ToString());
            }
            cmbDocType.SelectedIndex = 0;

            // 获取 CertificateNouns 类的类型
            Type type = typeof(CertificateNouns);
            // 获取该类的所有静态字段
            FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);

            foreach (FieldInfo field in fields)
            {
                // 获取字段的值
                object value = field.GetValue(null);
                string txtControlName = "txt" + field.Name;
                // 根据控件名称查找对应的文本框控件
                TextBox textBox = FindName(txtControlName) as TextBox;
                if (textBox != null)
                {
                    // 设置文本框的 Text 属性
                    textBox.Text = value.ToString();
                }
            }

            dpInspectionDate.SelectedDate = DateTime.Now;
        }
        public MainWindow()
        {
            InitializeComponent();
            GetSystemInfoByWMI();
            InitGUI();
        }

        private void SelectSystemInfoLogFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文本文件 (*.txt)|*.txt";
            if (openFileDialog.ShowDialog() == true)
            {
                txtSystemInfoLogPath.Text = openFileDialog.FileName;
            }

            FileController.UploadFile(txtSystemInfoLogPath.Text, Path.GetExtension(openFileDialog.FileName));
        }

        private void SelectMacfeeSnapshotFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图片文件 (*.jpg;*.png)|*.jpg;*.png";
            if (openFileDialog.ShowDialog() == true)
            {
                txtMacfeeSnapshotPath.Text = openFileDialog.FileName;
            }

            FileController.UploadFile(txtMacfeeSnapshotPath.Text, Path.GetExtension(openFileDialog.FileName));
        }

        private void SelectMacAddressSnapshotFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图片文件 (*.jpg;*.png)|*.jpg;*.png";
            if (openFileDialog.ShowDialog() == true)
            {
                txtMacAddressSnapshotPath.Text = openFileDialog.FileName;
            }

            FileController.UploadFile(txtMacAddressSnapshotPath.Text, Path.GetExtension(openFileDialog.FileName));
        }

        private async void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
            if(_certificateItem == null)
            {
                Guid guid = Guid.NewGuid();
                CertificateNouns.DocId = guid.ToString();

                CertificateNouns.DocType = cmbDocType.Text;
                CertificateNouns.Company = txtCompany.Text;
                CertificateNouns.EquipmentName = txtEquipmentName.Text;
                CertificateNouns.DeviceName = txtDeviceName.Text;
                CertificateNouns.OSName = txtOSName.Text;
                CertificateNouns.OSVersion = txtOSVersion.Text;
                CertificateNouns.AntiSoftName = txtAntiSoftName.Text;
                CertificateNouns.AntiScanName = txtAntiScanName.Text;
                CertificateNouns.AntiSoftVerison = txtAntiSoftVersion.Text;
                CertificateNouns.AntiScanVerison = txtAntiScanVersion.Text;
                CertificateNouns.InspectionDate = dpInspectionDate.SelectedDate;
                CertificateNouns.InspectorName = txtInspectorName.Text;
                CertificateNouns.SignName = txtSignName.Text;
                CertificateNouns.VendorName = txtVendorName.Text;
                CertificateNouns.Model = txtModel.Text;
                CertificateNouns.OSTypeVersion = txtOSTypeVersion.Text;
                CertificateNouns.ArchBit = txtAntiScanName.Text;
                CertificateNouns.ServicePack = txtServicePack.Text;
                CertificateNouns.LatestPatch = txtLatestPatch.Text;
                CertificateNouns.ComputerCount = int.Parse(txtComputerCount.Text);
                CertificateNouns.SystemInfoFilePath = txtSystemInfoLogPath.Text;
                CertificateNouns.McafeeFilePath = txtMacfeeSnapshotPath.Text;
                CertificateNouns.MacAddressFilePath = txtMacAddressSnapshotPath.Text;

                await _certificateService.submitForm();
            }
            else
            {
                CertificateNouns.DocType = cmbDocType.Text;
                CertificateNouns.Company = txtCompany.Text;
                CertificateNouns.EquipmentName = txtEquipmentName.Text;
                CertificateNouns.DeviceName = txtDeviceName.Text;
                CertificateNouns.OSName = txtOSName.Text;
                CertificateNouns.OSVersion = txtOSVersion.Text;
                CertificateNouns.AntiSoftName = txtAntiSoftName.Text;
                CertificateNouns.AntiScanName = txtAntiScanName.Text;
                CertificateNouns.AntiSoftVerison = txtAntiSoftVersion.Text;
                CertificateNouns.AntiScanVerison = txtAntiScanVersion.Text;
                CertificateNouns.InspectionDate = dpInspectionDate.SelectedDate;
                CertificateNouns.InspectorName = txtInspectorName.Text;
                CertificateNouns.SignName = txtSignName.Text;
                CertificateNouns.VendorName = txtVendorName.Text;
                CertificateNouns.Model = txtModel.Text;
                CertificateNouns.OSTypeVersion = txtOSTypeVersion.Text;
                CertificateNouns.ArchBit = txtAntiScanName.Text;
                CertificateNouns.ServicePack = txtServicePack.Text;
                CertificateNouns.LatestPatch = txtLatestPatch.Text;
                CertificateNouns.ComputerCount = int.Parse(txtComputerCount.Text);
                CertificateNouns.SystemInfoFilePath = txtSystemInfoLogPath.Text;
                CertificateNouns.McafeeFilePath = txtMacfeeSnapshotPath.Text;
                CertificateNouns.MacAddressFilePath = txtMacAddressSnapshotPath.Text;

                await _certificateService.updateForm(_certificateItem.Id);
            }
                
            _certificateItem = null;
            MessageBox.Show("数据提交成功！");
        }


        public void GetSystemInfoByWMI()
        {
            try
            {

                foreach (var os in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get())
                {
                    // 获取发行包名称
                    string caption = os["Caption"]?.ToString();
                    Entity.CertificateNouns.OSName = caption;
                    Entity.CertificateNouns.OSTypeVersion = Entity.CertificateNouns.OSName;

                    // 获取发行包构建版本和日期信息
                    string version = os["Version"]?.ToString();
                    string buildNumber = os["BuildNumber"]?.ToString();
                    string buildType = os["BuildType"]?.ToString();
                    string detailedInfo = $"{version} {buildType} Build {buildNumber}";
                    Entity.CertificateNouns.OSVersion = detailedInfo;

                    // 获取位数
                    string osArchitecture = os["OSArchitecture"]?.ToString();
                    if (!string.IsNullOrEmpty(osArchitecture))
                    {
                        Entity.CertificateNouns.ArchBit = osArchitecture;
                    }
                    else
                    {
                        Entity.CertificateNouns.ArchBit = "未能获取到计算机位数信息。";
                    }

                    // 获取服务包版本号
                    object majorVersionObj = os["ServicePackMajorVersion"];
                    object minorVersionObj = os["ServicePackMinorVersion"];

                    if (majorVersionObj != null && minorVersionObj != null)
                    {
                        int majorVersion = Convert.ToInt32(majorVersionObj);
                        int minorVersion = Convert.ToInt32(minorVersionObj);

                        if (majorVersion > 0 || minorVersion > 0)
                        {
                            Entity.CertificateNouns.ArchBit = $"{majorVersion}.{minorVersion}";
                        }
                        else
                        {
                            Console.WriteLine("未安装服务包。");
                        }
                    }
                    else
                    {
                        Console.WriteLine("未能获取到服务包信息。");
                    }


                }

                const string query = "SELECT HotFixID FROM Win32_QuickFixEngineering";
                var search = new ManagementObjectSearcher(query);
                var collection = search.Get();

                string hotfixID;
                int date_number = 0;
                foreach (ManagementObject quickFix in collection)
                {
                    hotfixID = quickFix["HotFixID"].ToString();
                    if (hotfixID.Contains("KB"))
                    {
                        string tmp = hotfixID.Substring(2);
                        int num = int.Parse(tmp);
                        if (date_number < num) date_number = num;
                    }
                }

                Entity.CertificateNouns.LatestPatch = "KB" + date_number.ToString();
            }
            catch (ManagementException ex)
            {
                // 处理 WMI 查询过程中可能出现的异常
                Console.WriteLine($"WMI 查询出错: {ex.Message}");
            }
        }

        private void OpenDocWindowButton_Click(object sender, RoutedEventArgs e)
        {
            // 创建 DocWindow 实例
            Window1 docWindow = new Window1();

            // 显示 DocWindow
            docWindow.Show();
        }

        public void SetDataToControls(CertificateItem item)
        {
            string docTypeText = item.DocType;
            bool isItemExists = false;
            foreach (var it in cmbDocType.Items)
            {
                if (it is ComboBoxItem comboBoxItem && comboBoxItem.Content.ToString() == docTypeText)
                {
                    cmbDocType.SelectedItem = comboBoxItem;
                    isItemExists = true;
                    break;
                }
            }
            // 如果 ComboBox 中不存在该值，则添加并选中它
            if (!isItemExists)
            {
                ComboBoxItem newItem = new ComboBoxItem { Content = docTypeText };
                cmbDocType.Items.Add(newItem);
                cmbDocType.SelectedItem = newItem;
            }

            txtCompany.Text = item.Company;
            txtEquipmentName.Text = item.EquipmentName;
            txtDeviceName.Text = item.DeviceName;
            txtOSName.Text = item.OsName;
            txtOSVersion.Text = item.OsVersion;
            txtAntiSoftName.Text = item.AntiSoftName;
            txtAntiScanName.Text = item.AntiScanName;
            txtAntiSoftVersion.Text = item.AntiSoftVersion;
            txtAntiScanVersion.Text = item.AntiScanVersion;
            string dateText = item.InspectionDate;
            if (DateTime.TryParse(dateText, out DateTime parsedDate))
            {
                dpInspectionDate.SelectedDate = parsedDate;
            }
            txtInspectorName.Text = item.InspectorName;
            txtSignName.Text = item.SignName;
            txtVendorName.Text = item.VendorName;
            txtModel.Text = item.Model;
            txtOSTypeVersion.Text = item.OsTypeVersion;
            txtArchBit.Text = item.ArchBit;
            txtServicePack.Text = item.ServicePack;
            txtLatestPatch.Text = item.LatestPatch;
            txtComputerCount.Text = item.ComputerCount.ToString();
            txtSystemInfoLogPath.Text = item.SystemInfoFilePath;
            txtMacfeeSnapshotPath.Text = item.McAfeeFilePath;
            txtMacAddressSnapshotPath.Text = item.MacAddressFilePath;
            txtRemark.Text = item.Remark;

            _certificateItem = item;
        }
    }
}